package pl.umk.mat.fred.unicore.urc.storagemanagement.analytics.MonitoredStreams;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;

public class MonitoredOutputStream extends OutputStream{

	private OutputStream dstStream;
	private Date start;
	private Date end;
	private boolean haveIStartDate = false;
	private boolean closed = false;
	
	public MonitoredOutputStream(OutputStream dstStream) {
		this.dstStream = dstStream;
	}
	
	@Override
	public void write(int b) throws IOException {
		if (!haveIStartDate) {
			start = new Date();
			haveIStartDate = true;
		}
		dstStream.write(b);
		end = new Date();
	}
	
	@Override
	public void write(byte[] b, int off, int len) throws IOException {
		if (!haveIStartDate) {
			start = new Date();
			haveIStartDate = true;
		}
		dstStream.write(b, off, len);
		end = new Date();
    }
	
	@Override
	public void close() throws IOException {
		if (closed) {
			throw new IOException("Already closed");
		}
		super.close();
		dstStream.close();
		closed = true;
	}
	
	public long getTransferTime() throws IllegalStateException {
		if ((start == null) || (end == null)) {
			throw new IllegalStateException("Writing was not executed");
		}
		return end.getTime() - start.getTime();
	}

}
